<!-- src/components/PostItem.vue -->
<template>
  <div class="post-item" @click="$emit('click')">
    <!-- 头部：用户信息 -->
    <div class="post-header">
      <el-avatar :size="36" :src="getAvatar()" />
      <div class="user-info">
        <span class="nickname">{{ post.nickname }}</span>
        <span class="time">{{ formatTimeAgo(post.time) }}</span>
      </div>
    </div>

    <!-- 内容 -->
    <div class="post-content">
      {{ truncateText(post.content, 80) }}
    </div>

    <!-- 评分 -->
    <div class="post-rating">
      <el-rate v-model="post.rating" disabled text-color="#ff9900" :max="5" />
    </div>

    <!-- 标签 -->
    <div class="post-tags">
      <el-tag
        v-for="tag in post.tags"
        :key="tag"
        size="small"
        type="info"
        style="margin-right: 6px; margin-bottom: 4px;"
      >
        #{{ tag }}
      </el-tag>
    </div>

    <!-- 统计信息 -->
    <PostStatsBar
      :views="post.views"
      :likes="post.likes"
      :liked="post.liked"
      @toggle-like="$emit('toggle-like')"
    />
  </div>
</template>

<script setup>
import PostStatsBar from './PostStatsBar.vue'
import { defineProps, defineEmits } from 'vue'

defineProps({
  post: {
    type: Object,
    required: true
  }
})

defineEmits(['click', 'toggle-like'])

// 工具函数
const getAvatar = () => {
  const avatars = [
    'https://cube.elemecdn.com/3/7c/3ea6beec64369c29f1a93c0ac8653.jpg',
    'https://cube.elemecdn.com/6/94/ae2e1b0fcb35bd936d75b56954eaf.jpeg',
    'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bc.png'
  ]
  return avatars[Math.floor(Math.random() * avatars.length)]
}

const formatTimeAgo = (timestamp) => {
  const now = Date.now()
  const diff = now - timestamp
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour

  if (diff < minute) return '刚刚'
  if (diff < hour) return `${Math.floor(diff / minute)}分钟前`
  if (diff < day) return `${Math.floor(diff / hour)}小时前`
  return `${Math.floor(diff / day)}天前`
}

const truncateText = (text, length) => {
  return text.length > length ? text.slice(0, length) + '...' : text
}
</script>

<style scoped>
.post-item {
  padding: 18px;
  border: 1px solid #eaeaea;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fcfcfc;
  margin-bottom: 16px;
}

.post-item:hover {
  border-color: #409eff;
  box-shadow: 0 4px 12px rgba(0, 102, 102, 0.1);
  transform: translateY(-2px);
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  margin-left: 12px;
}

.nickname {
  font-weight: 600;
  color: #006666;
  font-size: 15px;
}

.time {
  font-size: 12px;
  color: #999;
}

.post-content {
  font-size: 15px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 10px;
}

.post-rating {
  margin-bottom: 8px;
}

.post-tags {
  margin-bottom: 12px;
  display: flex;
  flex-wrap: wrap;
}
</style>